﻿using Commons;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.EntityFrameworkCore;
using RMSModel;
using RMSModel.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace RMS.Token
{
    public class WXApiFilter : Attribute, IActionFilter
    {
        private readonly RMSDB db;

        public WXApiFilter(RMSDB db)
        {
            this.db = db;
        }

        public void OnActionExecuted(ActionExecutedContext context)
        {
            //throw new NotImplementedException();
        }

        public void OnActionExecuting(ActionExecutingContext context)
        {
            ResultType result = new ResultType();
            string token = context.HttpContext.Request.Headers["X-Nideshop-Token"].ToString();
            if (string.IsNullOrEmpty(token))
            {
                result.ResultCode = 401;
                result.ResultMsg = "未登录,请登录";
                context.Result = new JsonResult(result);
                return;
            }
            var data = db.shopusertoken.FromSqlRaw(string.Format("select * from shopusertoken where token = '{0}'", token));
            if (data.Count() == 0)
            {
                result.ResultCode = 401;
                result.ResultMsg = "用户不存在，请重新登录";
                context.Result = new JsonResult(result);
                return;
            }
            shopusertoken usertoken = data.First();
            if (DateTime.Now > usertoken.expire_time)
            {
                result.ResultCode = 401;
                result.ResultMsg = "登录已过期，请重新登录";
                context.Result = new JsonResult(result);
                return;
            }
            context.ActionArguments.Add("userId", usertoken.user_id);
            
            usertoken.update_time = DateTime.Now;
            usertoken.expire_time = DateTime.Now.AddDays(30);
            db.shopusertoken.Update(usertoken);
            db.SaveChanges();
        } 
    }
}
